package com.corecloud.controller.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.entity.SysDeptEntity;
import com.corecloud.entity.SysUserEntity;
import com.corecloud.entity.SysUserRoleEntity;
import com.corecloud.service.SysDeptService;
import com.corecloud.service.SysUserRoleService;
import com.corecloud.service.SysUserService;
import com.corecloud.tools.OAuth2Utils;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;


/**
 * 类 名 称：OAuth2AppAPIController
 * 类 描 述：第三方相关API
 * @version 1.0.0
 */
@RestController
@RequestMapping(path = "/api",produces = {"application/json;charset=UTF-8"})
public class OAuth2AppAPIController {
	private final Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;


	@RequestMapping("/userinfo")
	public String queryLoginUserInfo(@RequestParam(value = "access_token") String at) throws UnsupportedEncodingException, SQLException {
		String jsonStr = "";
		if (at!=null) {
			String userName = OAuth2Utils.getUserNameByAccessToken(at);
			logger.info(">>>>第三方应用根据token查询出来的userName【"+userName+"】");
			if(!StringUtils.isEmpty(userName)) {
				Gson gson = new Gson();
				SysUserEntity user = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",userName));
				//回填并设置部分数据
				//user.setPassword(null);
				user.setAccount(userName);

				if(!StringUtils.isEmpty(user.getDeptId())){
					SysDeptEntity dept = sysDeptService.selectOne(new QueryWrapper<SysDeptEntity>().eq("id",user.getDeptId()));
					user.setDeptCode(dept.getDeptCode());
				}
				//回填用户角色编码
				List<SysUserRoleEntity> userRoleList = sysUserRoleService.getListByParas(new QueryWrapper<SysUserRoleEntity>().eq("user_id",user.getId()));
				if(userRoleList != null && userRoleList.size() > 0){
					String roles = "";
					for(int i = 0;i<userRoleList.size();i++){
						SysUserRoleEntity sur = userRoleList.get(i);
						roles += sur.getRoleCode()+",";
					}
					if(!StringUtils.isEmpty(roles)){
						roles = roles.substring(0,roles.length()-1);
					}
					user.setRoleCode(roles);
				}
				jsonStr = gson.toJson(user);
			}
		}
		return jsonStr;
	}
}
